package info.batcloud.fanli.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import info.batcloud.fanli.admin.permission.ManagerPermissions;
import info.batcloud.fanli.admin.permission.annotation.Permission;
import info.batcloud.fanli.core.constants.PddConstatns;
import info.batcloud.fanli.core.pdd.PddApp;
import info.batcloud.fanli.core.service.DdkService;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.settings.DdkAuthSetting;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import static info.batcloud.fanli.admin.permission.ManagerPermissions.COMMISSION_ORDER_MANAGE;

@Controller
@RequestMapping("/api/ddk")
public class DdkController {

    @Inject
    @Qualifier(PddConstatns.DDK_UNION)
    private PddApp pddApp;

    @Inject
    private SystemSettingService systemSettingService;

    @Inject
    private DdkService ddkService;

    @GetMapping("/auth")
    @Permission(ManagerPermissions.DDK_AUTH_SETTING)
    public String auth() {
        String redirectUrl = "http://jinbao.pinduoduo.com/open.html?client_id=%s&response_type=code&redirect_uri=%s";
        redirectUrl = String.format(redirectUrl, new String[]{pddApp.getClientId(), pddApp.getRedirectUrl(), "auth"});
        return "redirect:" + redirectUrl;
    }

    @GetMapping("/callback")
    public String callback(String code) throws IOException {

        String url = "http://open-api.pinduoduo.com/oauth/token";

        URL uri = new URL(url);

        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "application/json");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        JSONObject requestBody = new JSONObject();
        requestBody.put("grant_type", "authorization_code");
        requestBody.put("client_id", pddApp.getClientId());
        requestBody.put("client_secret", pddApp.getClientSecret());
        requestBody.put("redirect_uri", pddApp.getRedirectUrl());
        requestBody.put("code", code);
        //链接地址
        conn.connect();
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        //发送参数
        writer.write(JSON.toJSONString(requestBody));
        //清理当前编辑器的左右缓冲区，并使缓冲区数据写入基础流
        writer.flush();
        int responseCode = conn.getResponseCode();

        InputStream is = conn.getInputStream();

        String jsonStr = IOUtils.toString(is, "utf8");

        JSONObject jsonObject = JSON.parseObject(jsonStr);
        DdkAuthSetting ddkAuthSetting = systemSettingService.findActiveSetting(DdkAuthSetting.class);

        ddkAuthSetting.setAccessToken(jsonObject.getString("access_token"));
        ddkAuthSetting.setExpiresIn(new Date(System.currentTimeMillis() + jsonObject.getLong("expires_in") * 1000));
        ddkAuthSetting.setRefreshToken(jsonObject.getString("refresh_token"));
        ddkAuthSetting.setOwnerId(jsonObject.getString("owner_id"));
        ddkAuthSetting.setOwnerName(jsonObject.getString("owner_name"));
        systemSettingService.saveSetting(ddkAuthSetting, 0);
        systemSettingService.activeSetting(DdkAuthSetting.class, 0);
        conn.disconnect();
        return "redirect:/auto-close.html";

    }

    @GetMapping("/fetch-order")
    @Permission(COMMISSION_ORDER_MANAGE)
    @ResponseBody
    public Object fetchOrder(DdkService.OrderFetchParam param) {
        ddkService.fetchOrder(param);
        return 1;
    }
}
